package com.foreveross.fetl.core.domain.freight.repository.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.springframework.stereotype.Repository;

import com.foreveross.fetl.common.HBaseTable;
import com.foreveross.fetl.common.hbase.client.HBaseHelper;
import com.foreveross.fetl.common.jpa.EntityHibernateRepository;
import com.foreveross.fetl.core.domain.freight.AirChinaTaobaoEntity;
import com.foreveross.fetl.core.domain.freight.hbase.AgentEntity;
import com.foreveross.fetl.core.domain.freight.repository.IAirChinaTaobaoRepository;
import com.foreveross.fetl.util.DateUtils;
import com.foreveross.fetl.util.RowkeyUtils;

@Repository("airChinaTaobaoRepository")
public class AirChinaTaobaoRepositoryImpl extends EntityHibernateRepository
		implements IAirChinaTaobaoRepository {

	@Override
	public List<AirChinaTaobaoEntity> findByCondition(Date reportDate,
			Date flightDate, String fromCityCode, String toCityCode,
			String flightNo, String carrierKey, String hbaseKey) {
		StringBuffer jpql =new StringBuffer("select airChina from AirChinaTaobaoEntity airChina where 1=1 ");
		List<Object> conditionVals = new ArrayList<Object>();
		if(reportDate!=null){
			jpql.append(" and airChina.reportDate =? ");
			conditionVals.add(reportDate);
		}
		if(flightDate !=null){
			jpql.append(" and airChina.flightDate =? ");
			conditionVals.add(flightDate);
		}
		if(null!=fromCityCode && !"".equals(fromCityCode)){
			jpql.append(" and airChina.fromCityCode =? ");
			conditionVals.add(fromCityCode);
		}
		if(null!=toCityCode && !"".equals(toCityCode)){
			jpql.append(" and airChina.toCityCode =? ");
			conditionVals.add(toCityCode);
		}
		if(null!=flightNo && !"".equals(flightNo)){
			jpql.append(" and airChina.flightNo =? ");
			conditionVals.add(flightNo);
		}
		if(null!=hbaseKey && !"".equals(hbaseKey)){
			jpql.append(" and airChina.hbaseKey =? ");
			conditionVals.add(hbaseKey);
		}
		if(null!=carrierKey && !"".equals(carrierKey)){
			jpql.append(" and airChina.carrierKey =? ");
			conditionVals.add(carrierKey);
		}
	
		jpql.append(" order by airChina.createTime desc ");
		return super.queryResult(jpql.toString(), conditionVals.toArray());
		
	}

	@Override
	public int creatReport(List<String> channels,List<String> carrierKeys, String fromCity,
			String toCity, Date startTime, Date endTime, Date flightDate) {

//		PortEntity portEntity =new PortEntity();
//		portEntity=portEntity.findByFromCityCode(fromCity);
//		if(portEntity==null){
//			return 0;
//		}

		//String [] carrier_keys={"CA","CZ","MU","SC","3U","HU","ZH","MF"};
		List<AirChinaTaobaoEntity> listAir =new ArrayList<AirChinaTaobaoEntity>();
		for(String channel :channels){
			List<AirChinaTaobaoEntity> channelAir=null;
			channelAir= this.build(channel, fromCity, toCity, startTime,endTime, flightDate);
			if(null!=channelAir && !channelAir.isEmpty()){
				for(String carrierKey:carrierKeys){
					List<AirChinaTaobaoEntity> listCompanyAir=new ArrayList<AirChinaTaobaoEntity>();
					for(AirChinaTaobaoEntity entity:channelAir){
						if(entity.getFlightNo().startsWith(carrierKey)){
							listCompanyAir.add(entity);
						}
					}
					if(null!=listCompanyAir && !listCompanyAir.isEmpty()){
						AirChinaTaobaoEntity airChina =null;
						for(AirChinaTaobaoEntity en: listCompanyAir){
							if(null==airChina){
								if(null!=en.getAgentPrice()&& en.getAgentPrice()>0){
									airChina=en;
								}
							}else if(null!=en.getAgentPrice() && 0!=en.getAgentPrice() && en.getAgentPrice()<airChina.getAgentPrice()){
								airChina=en;
							}
						}
						if(null!=airChina && airChina.getAgentPrice()>0){
							listAir.add(airChina);
						}
					}
				}
			}
		}
		return this.saveList(listAir);
	}

	

	private List<AirChinaTaobaoEntity> build(String channel, 
			String fromCity, String toCity, Date startTime, Date endTime,
			Date flightDate) {
		List<AirChinaTaobaoEntity> listAir =new ArrayList<AirChinaTaobaoEntity>();
		Calendar cStart = Calendar.getInstance();
		cStart.setTime(startTime);
		Calendar cEnd = Calendar.getInstance();
		cEnd.setTime(endTime);
		while (cStart.before(cEnd)) {
			String startRowKey =RowkeyUtils.getRowKey(cStart.getTime(), channel,  fromCity, toCity, flightDate, RowkeyUtils.START_ROW_KEY);
			String endRowKey=RowkeyUtils.getRowKey(cStart.getTime(), channel,  fromCity, toCity, flightDate, RowkeyUtils.STOP_ROW_KEY);
			ResultScanner rs = null;
			try {
				rs = HBaseHelper.getRecords(HBaseTable.BASE_DATA_FLIGHT,
						startRowKey, endRowKey,new String[]{"planeinfo","agentInfos"},null);
				for (Result res : rs) {
					AirChinaTaobaoEntity air= this.buildAirChina(res,channel,startTime, flightDate);
					if(null!=air){
						listAir.add(air);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				if(rs != null) rs.close();
				rs = null;
			}
			cStart.add(Calendar.HOUR_OF_DAY, 1);// 开始时间加一小时
		}
		return listAir;
	}
	
	private AirChinaTaobaoEntity buildAirChina(Result res, String channel,
			Date startTime, Date flightDate) {
		Map<String, Map<String, String>> curMap = HBaseHelper
				.transformHBaseRowToMap(res);
		Map<String, String> curPalneInfoMap = curMap.get("planeinfo");
		double flightPrice = Float.parseFloat(curPalneInfoMap.get("lowerPrice") != null 
				 ? curPalneInfoMap.get("lowerPrice") : "0");
		if (flightPrice <= 0) {
			return null;
		}
		if(curPalneInfoMap.get("flightId")==null) return null;
		if(curPalneInfoMap.get("flightId").indexOf("|")>0){
			curPalneInfoMap.put("flightId", curPalneInfoMap.get("flightId").substring(0, curPalneInfoMap.get("flightId").indexOf("|")));
		}
		if(curPalneInfoMap.get("flightId").indexOf(",")>0){
			curPalneInfoMap.put("flightId", curPalneInfoMap.get("flightId").substring(0, curPalneInfoMap.get("flightId").indexOf(",")));
		}
		String flightNo =curPalneInfoMap.get("flightId");
		
		AirChinaTaobaoEntity entity =new AirChinaTaobaoEntity();
		entity.setReportDate(DateUtils.parse(DateUtils.format(startTime, "yyyyMMdd"), "yyyyMMdd"));
		entity.setFlightDate(DateUtils.parse(DateUtils.format(flightDate, "yyyyMMdd"), "yyyyMMdd"));
		entity.setFromCityCode(curPalneInfoMap.get("fromCity"));
		entity.setToCityCode(curPalneInfoMap.get("toCity"));
		entity.setFromCityName(curPalneInfoMap.get("fromCityName"));
		entity.setToCityName(curPalneInfoMap.get("toCityName"));
		entity.setCreateTime(new Date());
		entity.setFlightNo(flightNo);
		entity.setCarrierKey(flightNo.substring(0, 2));
		entity.setHbaseKey(channel);
		
		boolean isAgent=false;
		for(String infos : curMap.keySet()){
			if(infos.equalsIgnoreCase("agentInfos")){
				isAgent=true;
				 break;
			}
		}
		List<AgentEntity> listAgent=null;
		if(isAgent){
			listAgent=this.getAgnetList(curMap.get("agentInfos"));
		}
		if(null!=listAgent && !listAgent.isEmpty()){
			AgentEntity agent =null;
			for(AgentEntity en :listAgent){
				if(null!=en.getType()&& en.getType()==0){
					entity.setUltimatePrice(en.getPrice());//旗舰
				}
				if(null==agent || null==agent.getPrice() || agent.getPrice()==0){
					if( en.getType()!=0 && en.getPrice()>0){
						agent=en;
					}
				}else if(null!=en.getType() && en.getType()!=0 && null !=en.getPrice() && en.getPrice()>0 && en.getPrice()<agent.getPrice()){
					agent=en;
				}
			}
			if(null!=agent && null!=agent.getPrice() && agent.getPrice()!=0){
				entity.setAgentPrice(agent.getPrice());
			}
		}
		if(null==entity.getAgentPrice() ||entity.getAgentPrice()==0){
			entity.setAgentPrice(flightPrice);
		}
		return entity;
	}

	private List<AgentEntity> getAgnetList(Map<String, String> agentMap) {
		int max=0;
		for(String key :agentMap.keySet()){
			if(key.startsWith("name") || key.startsWith("price")){
				String[] strs =key.split("_");
				if(!isNumeric(strs[strs.length-1])){
					continue;
				}
			  int num = Integer.parseInt(strs[strs.length-1]);
			  if(num > max){
				  max = num;
			  }
			}
		}
		List<AgentEntity> list =new ArrayList<AgentEntity>();
		for (int i = 0; i < max+1; i++) {
			AgentEntity agentEntity =new AgentEntity();
			agentEntity.setName(agentMap.get("name_"+i));
			double price=Float.parseFloat(agentMap.get("price_"+i) != null 
					 ? agentMap.get("price_"+i) : "0");
			agentEntity.setPrice(price);
			agentEntity.setAddress(agentMap.get("address_"+i));
			agentEntity.setType(Integer.parseInt(agentMap.get("agentType_"+i) != null 
					 ? agentMap.get("agentType_"+i) : "9"));
			list.add(agentEntity);
		}
		List<AgentEntity> listAgent =new ArrayList<AgentEntity>();
		for(AgentEntity en :list){
			if(null!=en.getPrice() && 0!=en.getPrice()){
				listAgent.add(en);
			}
		}
		
		return listAgent;
	}

	private int saveList(List<AirChinaTaobaoEntity> listAir) {
		if(null==listAir || listAir.isEmpty())return 0;
		List<AirChinaTaobaoEntity> oldList= new ArrayList<AirChinaTaobaoEntity>();
		int i = 0;
		for(AirChinaTaobaoEntity entity : listAir){
			oldList.clear();
			oldList = this.findByCondition(entity.getReportDate(),
					entity.getFlightDate(), entity.getFromCityCode(),
					entity.getToCityCode(), null, entity.getCarrierKey(),
					entity.getHbaseKey());
			if(null!=oldList && oldList.size()>0){
				entity.setId(oldList.get(0).getId());
			}
			
			if(null!=entity.getUltimatePrice() && null!= entity.getAgentPrice() && entity.getUltimatePrice()>0 && entity.getAgentPrice()>0){
				entity.setSpreadAmount(entity.getUltimatePrice()-entity.getAgentPrice());
			}
			this.save(entity);
			i++;

		}
		return i;
	}

	/**
	 * 判断是否为数字    是 true
	 * @param str
	 * @return
	 */
   private   boolean isNumeric(String str){
			return str.matches("\\d*");    
		 } 
}
